//
//  UIImage+XYX.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/1.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit
import CoreGraphics
extension UIImage {
    class func load(name : String?)->UIImage?{
        guard name != nil else {
            return nil
        }
        var absolute = ""
        
        let scale = UIScreen.main.scale
        if scale == 3.0 {
            absolute = name! + "@3x"
        }else if scale == 2.0 {
            absolute = name! + "@2x"
        }
        if let path = Bundle.main.path(forResource: absolute, ofType: "png") {
            let url = URL.init(fileURLWithPath: path)
            do {
                let data = try Data.init(contentsOf: url, options: .uncached)
                let image = UIImage.init(data: data)
                return image
            } catch  {
                print(error)
            }
        }
        
        if let path = Bundle.main.path(forResource: absolute, ofType: "jpg") {
            let url = URL.init(fileURLWithPath: path)
            do {
                let data = try Data.init(contentsOf: url, options: .uncached)
                let image = UIImage.init(data: data)
                return image
            } catch  {
                print(error)
            }
        }
        return nil
    }
    
    func compress(size : CGSize) -> UIImage? {
        UIGraphicsBeginImageContext(size)
        self.draw(in: CGRect.init(origin: CGPoint.zero, size: size))
        let scale = UIScreen.main.scale
        let scaled = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return UIImage.init(cgImage: scaled!.cgImage!, scale: scale, orientation: UIImageOrientation.up)
    }
    
    class func image(color : UIColor,size : CGSize)->UIImage?{
        UIGraphicsBeginImageContext(size);
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(CGRect.init(origin: CGPoint.zero, size: size))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
